local Piece = require "packages.chess-games.xiangqi.core.piece"

local Rook = Piece:subclass("Xiangqi.Rook")

function Rook:initialize(id)
  Piece.initialize(self, id)

  self.name = 'rook'
  self.redStr = '车'
  self.blackStr = '车'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function Rook:canMoveTo(board, fromX, fromY, x, y)
  -- 不能移动到自己所在的位置
  if fromX == x and fromY == y then
    return false
  end

  -- 必须同行或同列
  if fromX ~= x and fromY ~= y then
    return false
  end

  -- 判断路径上是否有棋子
  if fromX == x then
    -- 同列，检查纵向路径
    local step = (y > fromY) and 1 or -1
    for j = fromY + step, y - step, step do
      if board[j][x] ~= 0 then
        return false
      end
    end
  else
    -- 同行，检查横向路径
    local step = (x > fromX) and 1 or -1
    for i = fromX + step, x - step, step do
      if board[fromY][i] ~= 0 then
        return false
      end
    end
  end

  -- 如果目标位置有己方棋子，也不能走
  local targetId = board[y][x]
  if targetId ~= 0 then
    local myColor = self:getColor()
    local targetColor = (targetId > 0) and "red" or "black"
    if myColor == targetColor then
      return false
    end
  end

  return true
end

return Rook
